//
//  NewsDetailViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/15.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "NewsDetailViewController.h"
#import "NewsDetailModel.h"
#import <MJRefresh/MJRefresh.h>
#import "UIImageView+WebCache.h"
//#import "JKTopWindowViewController.h"
#import "CommentViewController.h"
#import "NewsDetailSectionModel.h"
#import "JKBrowserViewController.h"
#import "NewsDetailExtraModel.h"
#import "JKImageBrowserView.h"
#import "NewsListModel.h"
#import "JKShareView.h"
#import "JKBottomLabel.h"
#import "SectionViewController.h"
#import "SQLiteManager.h"
#import "NewsListGetDataModel.h"
#import "NumberChangeAnimationView.h"
#import "JKProgressHUD.h"
#import "MainTableViewController.h"

#import "NetworkingTool.h"

#define TopScrollDistance (54.0 + (JKIsIphoneX ? 24 : 0))

@import WebKit;

@interface NewsDetailViewController () <UIScrollViewDelegate, WKNavigationDelegate>
{// readonly成员变量
    CGFloat _topImageHeight;
    CGFloat _scrollInsetTop;
}

/** 详情模型数据 */
@property (nonatomic, strong) NewsDetailModel *model;

/** 扩展数据模型 */
@property (nonatomic, strong) NewsDetailExtraModel *extraModel;

/** webView */
@property (weak, nonatomic) WKWebView *webView;

/** 状态栏 */
@property (weak, nonatomic) UIView *topStatusBar;

/** 点赞数按钮 */
@property (weak, nonatomic) IBOutlet UIButton *zanButton;

/** 点赞数label */
@property (weak, nonatomic) IBOutlet UILabel *popularityLabel;

/** 评论数label */
@property (weak, nonatomic) IBOutlet UILabel *commentCountLable;

/** 底部的工具条 */
@property (weak, nonatomic) IBOutlet UIView *bottomBarView;

/** 下一条新闻按钮 */
@property (weak, nonatomic) IBOutlet UIButton *nextStoryBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHCons;

/** 点赞后做动画的view */
@property (weak, nonatomic) NumberChangeAnimationView *zanAnimationView;

/** 顶部图片 */
@property (nonatomic, weak) UIImageView *topImageView;

/** 图片来源label */
@property (nonatomic, weak) UILabel *imageSourceLabel;

/** 标题label */
@property (nonatomic, weak) JKBottomLabel *titleLabel;

/** 底部本文来自xxx合集view */
@property (nonatomic, weak) UIView *bottomContainerView;

/** 底部本文来自xxx合集view上的label */
@property (nonatomic, weak) UILabel *bottomContainerViewLabel;

/** 底部本文来自xxx合集view上的imageView */
@property (nonatomic, weak) UIImageView *bottomContainerViewImgView;

/** 当前皮肤模式 */
@property (nonatomic, copy) NSString *currentSkinModel;

/** 夜间模式遮盖view */
@property (nonatomic, weak) UIView *coverView;

/** 顶部图片的高度 */
@property (nonatomic, assign, readonly) CGFloat topImageHeight;

/** scrollView顶部内边距 */
@property (nonatomic, assign, readonly) CGFloat scrollInsetTop;

/** 下一条索引 */
@property (nonatomic, strong) NSIndexPath *nextIndexPath;

/** 上一条索引 */
@property (nonatomic, strong) NSIndexPath *previousIndexPath;

/** 顶部刷新控件 */
@property (nonatomic, weak) UIView *refreshHeaderView;

/** 顶部刷新控件中的label */
@property (nonatomic, weak) UILabel *refreshHeaderViewLb;

/** 顶部刷新控件中的图标 */
@property (nonatomic, weak) UIImageView *refreshHeaderViewImgV;

/** 底部刷新控件 */
@property (nonatomic, weak) UIView *refreshFooterView;

/** 底部刷新控件中的label */
@property (nonatomic, weak) UILabel *refreshFooterViewLb;

/** 底部刷新控件中的图标 */
@property (nonatomic, weak) UIImageView *refreshFooterViewImgV;

/** 正在加载的图标 */
@property (nonatomic, weak) UIActivityIndicatorView *loadingIndicatorView;

/** request */
@property (nonatomic, strong) NSURLRequest *request;

/** 是否已经手动滑动过 */
@property (nonatomic, assign) BOOL isDragged;
@end

@implementation NewsDetailViewController

/** topImageView的Y值 -60 */
static CGFloat const topImageViewY = -60;

static NSInteger currentStatusBarStyle = 1;

#pragma mark - 懒加载
- (UIView *)refreshFooterView{
    if (!_refreshFooterView) {
        UIView *refreshFooterView = [[UIView alloc] init];
        refreshFooterView.backgroundColor = [UIColor clearColor];
        refreshFooterView.hidden = YES;
        refreshFooterView.frame = CGRectMake(0, JKScreenH, JKScreenW, JKBarHeight);
        [self.webView.scrollView addSubview:refreshFooterView];
        
        UIImageView *arrowImgV = [[UIImageView alloc] init];
        arrowImgV.image = [UIImage imageNamed:@"ZHAnswerViewBackIcon"];
        [refreshFooterView addSubview:arrowImgV];
        self.refreshFooterViewImgV = arrowImgV;
        
        UILabel *stateLabel = [[UILabel alloc] init];
        stateLabel.backgroundColor = [UIColor clearColor];
        stateLabel.textColor = JKColor(218, 218, 218);
        stateLabel.font = [UIFont systemFontOfSize:13];
        [refreshFooterView addSubview:stateLabel];
        self.refreshFooterViewLb = stateLabel;
        
        _refreshFooterView = refreshFooterView;
    }
    return _refreshFooterView;
}

- (UIView *)refreshHeaderView{
    if (!_refreshHeaderView) {
        UIView *refreshHeaderView = [[UIView alloc] init];
        refreshHeaderView.backgroundColor = [UIColor clearColor];
        refreshHeaderView.frame = CGRectMake(0, -self.scrollInsetTop - JKBarHeight, JKScreenW, JKBarHeight);
        [self.webView.scrollView addSubview:refreshHeaderView];
        
        UIImageView *arrowImgV = [[UIImageView alloc] init];
        arrowImgV.image = [UIImage imageNamed:@"ZHAnswerViewPrevIcon"];
        [refreshHeaderView addSubview:arrowImgV];
        self.refreshHeaderViewImgV = arrowImgV;
        
        UILabel *stateLabel = [[UILabel alloc] init];
        stateLabel.backgroundColor = [UIColor clearColor];
        stateLabel.textColor = JKColor(218, 218, 218);
        stateLabel.font = [UIFont systemFontOfSize:13];
        [refreshHeaderView addSubview:stateLabel];
        self.refreshHeaderViewLb = stateLabel;
        
        _refreshHeaderView = refreshHeaderView;
    }
    return _refreshHeaderView;
}

- loadingIndicatorView{
    if (!_loadingIndicatorView) {
        UIActivityIndicatorView *loadingIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
        loadingIndicatorView.center = CGPointMake(JKScreenW * 0.5, JKScreenH * 0.5);
        loadingIndicatorView.hidden = YES;
        [self.view addSubview:loadingIndicatorView];
        _loadingIndicatorView = loadingIndicatorView;
    }
    return _loadingIndicatorView;
}

- (NumberChangeAnimationView *)zanAnimationView{
    if (!_zanAnimationView) {
        NumberChangeAnimationView *zanAnimationView = [[NumberChangeAnimationView alloc] init];
        zanAnimationView.frame = CGRectMake((JKScreenW - 100) * 0.5, JKScreenH - JKBarHeight, 100, 26);
        zanAnimationView.hidden = YES;
        [self.view addSubview:zanAnimationView];
        _zanAnimationView = zanAnimationView;
    }
    return _zanAnimationView;
}

- (UIView *)topStatusBar{
    if (!_topStatusBar) {
        UIView *topStatusBar = [[UIView alloc] init];
        topStatusBar.hidden = YES;
        [self.view addSubview:topStatusBar];
        _topStatusBar = topStatusBar;
    }
    return _topStatusBar;
}

- (WKWebView *)webView{
    if (!_webView) {
        // 解决内存泄露问题
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
        config.selectionGranularity = WKSelectionGranularityCharacter;
        
        // 让网页内容自适应大小
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); ('meta[name=description]').remove(); ('head').append( '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1,user-scalable=no\">' );";
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
        
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        //        [wkUController addScriptMessageHandler:self name:@"openInfo"];
        config.userContentController = wkUController;
        
        // 创建WKWebView
        WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        [webView.scrollView jk_adapt_iOS_11_scrollView];
        webView.backgroundColor = [UIColor whiteColor];
        webView.scrollView.backgroundColor = [UIColor clearColor];
        webView.navigationDelegate = self;
        webView.scrollView.contentInset = UIEdgeInsetsMake(self.scrollInsetTop, 0, 0, 0);
        webView.scrollView.delegate = self;
        if ([webView respondsToSelector:@selector(setAllowsLinkPreview:)]) {
            webView.allowsLinkPreview = YES;
        }
        webView.scrollView.mj_footer = [MJRefreshBackFooter footerWithRefreshingTarget:nil refreshingAction:nil];
        [self.view insertSubview:webView atIndex:0];
        _webView = webView;
        
        UIView *whiteView = [[UIView alloc] init];
        whiteView.backgroundColor = [UIColor whiteColor];
        whiteView.frame = CGRectMake(0, 0, JKScreenW, -topImageViewY);
        [webView.scrollView insertSubview:whiteView atIndex:1];
        
        UIImageView *topImageView = [[UIImageView alloc] init];
        topImageView.frame = CGRectMake(0, -self.scrollInsetTop + topImageViewY, JKScreenW, self.topImageHeight);
        [webView.scrollView insertSubview:topImageView atIndex:0];
        self.topImageView = topImageView;
        
        topImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *topImageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topImageTap:)];
        [topImageView addGestureRecognizer:topImageTap];
        
        UIImageView *maskImageView = [[UIImageView alloc] init];
        maskImageView.frame = topImageView.bounds;
        maskImageView.image = [UIImage imageNamed:@"Home_Image_Mask_Plus"];
        [self.topImageView addSubview:maskImageView];
        
        UILabel *imageSourceLabel = [[UILabel alloc] init];
        imageSourceLabel.backgroundColor = [UIColor clearColor];
        imageSourceLabel.textColor = [UIColor whiteColor];
        imageSourceLabel.textAlignment = NSTextAlignmentRight;
        imageSourceLabel.font = [UIFont systemFontOfSize:9];
        [webView.scrollView addSubview:imageSourceLabel];
        self.imageSourceLabel = imageSourceLabel;
        
        JKBottomLabel *titleLabel = [[JKBottomLabel alloc] init];
        [titleLabel setVerticalAlignment:(VerticalAlignmentBottom)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.textAlignment = NSTextAlignmentLeft;
        titleLabel.font = [UIFont boldSystemFontOfSize:19];
        titleLabel.numberOfLines = 0;
        titleLabel.shadowColor = [UIColor darkGrayColor];
        titleLabel.shadowOffset = CGSizeMake(1, 0);
        titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
        [webView.scrollView addSubview:titleLabel];
        self.titleLabel = titleLabel;
        
        webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(self.scrollInsetTop, 0, 0, 0);
        webView.scrollView.scrollEnabled = NO;
    }
    return _webView;
}

- (void)topImageTap:(UITapGestureRecognizer *)tap{
    [JKImageBrowserView showWithImage:self.topImageView.image];
}

- (CGFloat)scrollInsetTop{
    if (!_scrollInsetTop) {
        _scrollInsetTop = self.topImageHeight + 2 * topImageViewY;
    }
    return _scrollInsetTop;
}

- (CGFloat)topImageHeight{
    if (!_topImageHeight) {
        _topImageHeight = JKScreenW * 0.85;
    }
    return _topImageHeight;
}

- (UIView *)bottomContainerView{
    if (!_bottomContainerView) {
        // 添加bottomeView
        UIView *bottomContainerView = [[UIView alloc] init];
        bottomContainerView.frame = CGRectMake(JKMarginTen * 2, 0, JKScreenW - JKMarginTen * 4, JKBarHeight);
        bottomContainerView.hidden = YES;
        [self.webView.scrollView addSubview:bottomContainerView];
        
        // 左侧图片
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:(CGRectMake(1, 1, JKBarHeight-2, JKBarHeight-2))];
        [bottomContainerView addSubview:imgView];
        self.bottomContainerViewImgView = imgView;
        
        // 右侧label
        UILabel *label = [[UILabel alloc] init];
        label.frame = CGRectMake(JKBarHeight + JKMarginTen, JKMarginTen, bottomContainerView.width - JKBarHeight - JKMarginTen, JKBarHeight - JKMarginTen * 2);
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:13];
        [bottomContainerView addSubview:label];
        self.bottomContainerViewLabel = label;
        
        // 当然这里也可以用手势，但是手势太多，可能会出问题吧。。
        UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        btn.frame = bottomContainerView.bounds;
        [bottomContainerView addSubview:btn];
        [btn addTarget:self action:@selector(tapbottomContainerView) forControlEvents:(UIControlEventTouchUpInside)];
        
        _bottomContainerView = bottomContainerView;
    }
    return _bottomContainerView;
}

- (UIView *)coverView{
    if (!_coverView) {
        UIView *coverView = [[UIView alloc] init];
        coverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        coverView.userInteractionEnabled = NO;
        [self.view addSubview:coverView];
        _coverView = coverView;
    }
    return _coverView;
}

#pragma mark - 生命周期方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self updateSkin];
    
    [[UIApplication sharedApplication] setStatusBarStyle:(UIStatusBarStyleLightContent) animated:YES];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [[UIApplication sharedApplication] setStatusBarStyle:currentStatusBarStyle animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.bottomViewHCons.constant = JKIsIphoneX ? 44 + JKHomeIndicatorHeight : 44;
    
    [self setup];
    
    [self loadData];
    
    if (self.is3DTouchJump) {
        self.nextStoryBtn.enabled = NO;
        return;
    }
    
    [self calculateNextIndexPath];
    
    [self calculatePreviousIndexPath];
}

- (void)setup{
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.loadingIndicatorView.hidden = NO;
    [self.loadingIndicatorView startAnimating];
    
    UIScreenEdgePanGestureRecognizer *swipe = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)];
    swipe.edges = UIRectEdgeRight;
    
    [self.webView addGestureRecognizer:swipe];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    
    // 右划返回手势
    //    id target = self.navigationController.interactivePopGestureRecognizer.delegate;
    //    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:target action:@selector(handleNavigationTransition:)];
    //    [self.view addGestureRecognizer:pan];
    //    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    if (![SQLiteManager queryIsLikedWithStoryID:self.storyID]) return;
    self.zanButton.selected = YES;
    self.popularityLabel.textColor = self.commentCountLable.backgroundColor;
}

- (void)swipe:(UIScreenEdgePanGestureRecognizer *)swipe{
    
    if (swipe.state == UIGestureRecognizerStateBegan) {
        
        [self commentClick:nil];
        JKLog(@"UIGestureRecognizerStateBegan");
    }
}

- (NSArray<id<UIPreviewActionItem>> *)previewActionItems{
    UIPreviewAction *action1 = [UIPreviewAction actionWithTitle:@"收藏" style:(UIPreviewActionStyleDefault) handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        [self collectStory];
    }];
    
    UIPreviewAction *action2 = [UIPreviewAction actionWithTitle:@"取消" style:(UIPreviewActionStyleDefault) handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    return @[action1, action2];
}

- (void)collectStory{
    
    if ([SQLiteManager queryIsCollectedWithStoryID:self.model.ID]) {
        
        [JKProgressHUD showErrorWithStatus:@"您已收藏该文章！"];
        
        return;
    }
    
    if ([SQLiteManager updateCollectedStatusWithStoryID:self.model.ID collected:YES]) {
        
        [JKProgressHUD showSuccessWithStatus:@"收藏成功！"];
        
        return;
    }
    
    [JKProgressHUD showErrorWithStatus:@"收藏失败！"];
}

//- (void)handleNavigationTransition:(id)sender{}

// 加载数据
- (void)loadData{
    [NewsListGetDataModel loadDetailDataWithID:self.storyID detailBlock:^(NewsDetailModel *detailModel, NSError *error) {
        if (error) {
            [self.loadingIndicatorView stopAnimating];
        }
        
        self.model = detailModel;
        
        [self loadDetailView:detailModel];
        
        if (self.model.section != nil) {
            
            [self bottomContainerView];
            [self.bottomContainerViewImgView sd_setImageWithURL:[NSURL URLWithString:self.model.section.thumbnail] placeholderImage:[UIImage imageNamed:@"Setting_Avatar"]];
            NSString *lbText = [NSString stringWithFormat:@"本文来自:  %@ · 合集", self.model.section.name];
            self.bottomContainerViewLabel.text = lbText;
        }
        
    } extraBlock:^(NewsDetailExtraModel *extraModel, NSError *error) {
        
        self.extraModel = extraModel;
        
        self.commentCountLable.text = @(extraModel.comments).stringValue;
        int popularity = extraModel.popularity;
        popularity = [SQLiteManager queryIsLikedWithStoryID:self.storyID] ? popularity + 1 : popularity;
        self.popularityLabel.text = @(popularity).stringValue;
    }];
}

// 计算下一篇文字索引
- (void)calculateNextIndexPath{
    
    if (self.indexPath == nil) {
        return;
    }
    
    self.nextStoryBtn.enabled = YES;
    
    NSIndexPath *nextIndexPath = nil;
    
    if (self.stories != nil) {
        
        NSArray *sectionArr = self.stories[self.indexPath.section];
        
        if (self.indexPath.row < sectionArr.count - 1) {
            
            nextIndexPath = [NSIndexPath indexPathForRow:self.indexPath.row + 1 inSection:self.indexPath.section];
            
        }else if (self.indexPath.section < self.stories.count - 1) {
            
            nextIndexPath = [NSIndexPath indexPathForRow:0 inSection:self.indexPath.section + 1];
            
        }else{
            
            self.nextStoryBtn.enabled = NO;
        }
        
    }else if (self.themeStories != nil) {
        
        if (self.indexPath.row < self.themeStories.count - 1) {
            
            nextIndexPath = [NSIndexPath indexPathForRow:self.indexPath.row + 1 inSection:0];
            
        }else{
            
            self.nextStoryBtn.enabled = NO;
        }
    }
    
    self.nextIndexPath = nextIndexPath;
}

// 计算上一篇文字索引
- (void)calculatePreviousIndexPath{
    
    if (self.indexPath == nil) {
        return;
    }
    
    NSIndexPath *previousIndexPath;
    
    if (self.stories != nil) {
        
        if (self.indexPath.row > 0) {
            
            previousIndexPath = [NSIndexPath indexPathForRow:self.indexPath.row - 1 inSection:self.indexPath.section];
            
        }else if (self.indexPath.section > 0) {
            
            NSArray *sectionArr = self.stories[self.indexPath.section - 1];
            previousIndexPath = [NSIndexPath indexPathForRow:sectionArr.count - 1 inSection:self.indexPath.section - 1];
            
        }else{
            
            previousIndexPath = nil;
        }
        
    }else if (self.themeStories != nil) {
        
        if (self.indexPath.row > 0) {
            
            previousIndexPath = [NSIndexPath indexPathForRow:self.indexPath.row - 1 inSection:0];
            
        }else{
            
            previousIndexPath = nil;
        }
    }
    
    self.previousIndexPath = previousIndexPath;
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    self.topStatusBar.frame = CGRectMake(0, 0, JKScreenW, JKStatusBarHeight);
    
    self.webView.frame = CGRectMake(0, 0, JKScreenW, JKScreenH - self.bottomViewHCons.constant);
    
    self.titleLabel.frame = CGRectMake(15, -25 - 100, JKScreenW - 30, 100);
    
    self.imageSourceLabel.frame = CGRectMake(0, -20, JKScreenW - 15, 12);
    
    self.coverView.frame = CGRectMake(0, 0, JKScreenW, JKScreenH - self.bottomViewHCons.constant);
    
    [self setupHeaderFooter];
}

- (void)setupHeaderFooter{
    
    if (self.is3DTouchJump) return;
    
    // header
    self.refreshHeaderViewImgV.frame = (self.previousIndexPath == nil) ? CGRectMake(0, 0, 0, 0) : CGRectMake(self.refreshHeaderView.width * 0.5 - 47, 12, 15, 20);
    self.refreshHeaderViewLb.frame = (self.previousIndexPath == nil) ? CGRectMake(0, 0, self.refreshHeaderView.width, self.refreshHeaderView.height) : CGRectMake(self.refreshHeaderView.width * 0.5 - 24, 0, 200, self.refreshHeaderView.height);
    self.refreshHeaderViewLb.textAlignment = (self.previousIndexPath == nil) ? NSTextAlignmentCenter : NSTextAlignmentLeft;
    self.refreshHeaderViewLb.text = (self.previousIndexPath == nil) ? @"已经是第一篇了" : @"载入上一篇";
    
    // footer
    self.refreshFooterViewImgV.frame = (self.nextIndexPath == nil) ? CGRectMake(0, 0, 0, 0) : CGRectMake(self.refreshFooterView.width * 0.5 - 47, 12, 15, 20);
    self.refreshFooterViewLb.frame = (self.nextIndexPath == nil) ? CGRectMake(0, 0, self.refreshFooterView.width, self.refreshFooterView.height) : CGRectMake(self.refreshFooterView.width * 0.5 - 24, 0, 200, self.refreshFooterView.height);
    self.refreshFooterViewLb.textAlignment = (self.nextIndexPath == nil) ? NSTextAlignmentCenter : NSTextAlignmentLeft;
    self.refreshFooterViewLb.text = (self.nextIndexPath == nil) ? @"已经是最后一篇了" : @"载入下一篇";
}

// 加载详情
- (void)loadDetailView:(NewsDetailModel *)model{
    NSString *body = model.body;
    if (body != nil) {
        NSString *tmpStr = @"";
        for (NSString *c in model.css) {
            
            [SQLiteManager cacheStoryDetailCssWithID:model.ID cssUrlStr:c];
            
            NSString *cssPath = [JKCssDirectory stringByAppendingPathComponent:[@(model.ID).stringValue stringByAppendingString:@".css"]];
            
            BOOL isCached = [[NSFileManager defaultManager] fileExistsAtPath:cssPath];
            
            if (isCached) {
                
                NSString *cssStr = [NSString stringWithContentsOfFile:cssPath encoding:NSUTF8StringEncoding error:nil];
                
                tmpStr = [NSString stringWithFormat:@"<style> %@ </style>", cssStr];
                
            }else{
                
                tmpStr = [NSString stringWithFormat:@"<link href='%@' rel='stylesheet' type='text/css' />%@", c, tmpStr];
            }
            
            // 由于它的CSS中已经写死了 顶部图片的高度就是200,可以自己来改
            body = [NSString stringWithFormat:@"%@ <style> .headline .img-place-holder { height: 0px;}</style> %@", tmpStr, body];
            // .content-wrap {background: #2E2E2E;}
            [self.webView loadHTMLString:body baseURL:nil];
        }
        
    }else{
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:model.share_url]];
        self.request = request;
        [self.webView loadRequest:self.request];
    }
    
    self.titleLabel.text = model.title;
    
    if (model.image_source != nil) {
        self.imageSourceLabel.text = [@"图片:  " stringByAppendingFormat:@"%@", model.image_source];
    }
    
    if (model.image != nil) {
        [self.topImageView sd_setImageWithURL:[NSURL URLWithString:model.image] placeholderImage:[UIImage imageNamed:@"Image_Preview"]];
        return;
    }
    
    if (!model.images) {
        [self.topImageView sd_setImageWithURL:[NSURL URLWithString:self.backgroundImageUrl] placeholderImage:[UIImage imageNamed:@"Image_Preview"]];
        return;
    }
    [self.topImageView sd_setImageWithURL:[NSURL URLWithString:model.images[0]] placeholderImage:[UIImage imageNamed:@"Image_Preview"]];
}

#pragma mark - 按钮点击
- (IBAction)backBtnClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

// 下一条
- (IBAction)nextStoryClick:(id)sender {
    
    if (!self.nextIndexPath) return;
    
    NewsDetailViewController *nextVc = [[NewsDetailViewController alloc] init];
    nextVc.storyListVc = self.storyListVc;
    
    NewsListModel *listModel = nil;
    
    if (self.stories != nil) {
        
        nextVc.stories = self.stories;
        listModel = self.stories[self.nextIndexPath.section][self.nextIndexPath.row];
        
    }else if (self.themeStories != nil) {
        
        nextVc.themeStories = self.themeStories;
        listModel = self.themeStories[self.nextIndexPath.row];
    }
    
    nextVc.storyID = listModel.ID;
    nextVc.backgroundImageUrl = self.backgroundImageUrl;
    nextVc.indexPath = self.nextIndexPath;
    
    [UIView  beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.75];
    [self.navigationController pushViewController:nextVc animated:NO];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.navigationController.view cache:NO];
    [UIView commitAnimations];
    
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

// 上一条
- (void)previousStory{
    
    if (!self.previousIndexPath) return;
    
    NewsDetailViewController *preVc = [[NewsDetailViewController alloc] init];
    preVc.storyListVc = self.storyListVc;
    
    NewsListModel *listModel = nil;
    
    if (self.stories != nil) {
        preVc.stories = self.stories;
        listModel = self.stories[self.previousIndexPath.section][self.previousIndexPath.row];
        
    }else if (self.themeStories != nil) {
        preVc.themeStories = self.themeStories;
        listModel = self.themeStories[self.previousIndexPath.row];
    }
    
    preVc.storyID = listModel.ID;
    preVc.backgroundImageUrl = self.backgroundImageUrl;
    preVc.indexPath = self.previousIndexPath;
    
    [UIView  beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.75];
    [self.navigationController pushViewController:preVc animated:NO];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:NO];
    [UIView commitAnimations];
    
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

- (IBAction)zanClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        
        [UIView animateWithDuration:0.2 animations:^{
            
            sender.transform = CGAffineTransformMakeScale(1.5, 1.5);
            
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:0.2 animations:^{
                
                sender.transform = CGAffineTransformIdentity;
                
            } completion:^(BOOL finished) {
                
            }];
        }];
    }
    
    [SQLiteManager updateIsLikedWithStoryID:self.storyID isLiked:sender.selected];
    
    if (!sender.selected) {
        self.popularityLabel.textColor = [UIColor lightGrayColor];
        self.popularityLabel.text = @(self.extraModel.popularity).stringValue;
        return;
    }
    
    self.zanAnimationView.hidden = NO;
    self.zanAnimationView.originalNumber = self.extraModel.popularity;
    
    self.popularityLabel.text = @(self.extraModel.popularity + 1).stringValue;
    self.popularityLabel.textColor = JKColor(29, 171, 239);
    
    [self.zanAnimationView beginAnimationWithTransform:CGAffineTransformMakeTranslation(0, -self.zanAnimationView.height * 1.5 - (JKIsIphoneX ? JKHomeIndicatorHeight : 0)) complete:nil];
}

- (IBAction)shareBtnClick:(id)sender {
    [JKShareView showWithModel:self.model];
}

- (IBAction)commentClick:(id)sender {
    CommentViewController *cmtVc = [[CommentViewController alloc] init];
    cmtVc.storyID = self.storyID;
    cmtVc.extraModel = self.extraModel;
    [self.navigationController pushViewController:cmtVc animated:YES];
}

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.topStatusBar.hidden = !(scrollView.contentOffset.y >= 0);
    
    [UIView animateWithDuration:0.25 animations:^{
        self.refreshFooterViewImgV.transform = (self.webView.scrollView.mj_footer.state == MJRefreshStatePulling) ? CGAffineTransformMakeRotation(M_PI-0.001) : CGAffineTransformIdentity;
    }];
    
    if (scrollView.contentOffset.y < -self.scrollInsetTop) {
        
        self.webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        
    }else {
        self.webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(self.scrollInsetTop, 0, 0, 0);
    }
    
    if (scrollView.contentOffset.y > -self.scrollInsetTop + 30 && self.isDragged) {
        // 设置下一篇控件
        
        self.refreshFooterView.hidden = NO;
        
        if (self.model.section != nil) {
            // 添加详情底部合集view
            self.bottomContainerView.y = self.webView.scrollView.mj_footer.frame.origin.y;
            self.refreshFooterView.y = self.bottomContainerView.y + 30 + JKBarHeight;
            self.bottomContainerView.hidden = NO;
            
        }else{
            self.refreshFooterView.y = self.webView.scrollView.mj_footer.y;
            self.refreshFooterView.hidden = NO;
        }
    }
    
    if (scrollView.contentOffset.y > JKScreenH) return;
    
    [UIView animateWithDuration:0.25 animations:^{
        self.refreshHeaderViewImgV.transform = ((-self.scrollInsetTop - scrollView.contentOffset.y) / TopScrollDistance >= 1) ? CGAffineTransformMakeRotation(M_PI+0.001) : CGAffineTransformIdentity;
    }];
    
    self.refreshHeaderView.y = (-self.scrollInsetTop - JKBarHeight) + (scrollView.contentOffset.y + self.scrollInsetTop) * 0.2;
    
    self.topImageView.y = -self.scrollInsetTop + topImageViewY + (scrollView.contentOffset.y + self.scrollInsetTop) * 0.5;
    
    scrollView.contentOffset = (scrollView.contentOffset.y <= -self.topImageHeight) ? CGPointMake(0, -self.topImageHeight) : CGPointMake(0, scrollView.contentOffset.y);
    
    if ([self.currentSkinModel isEqualToString:JKNightSkinModelValue]) return;
    
    UIStatusBarStyle style = (scrollView.contentOffset.y >= 0) ? UIStatusBarStyleDefault : UIStatusBarStyleLightContent;
    [[UIApplication sharedApplication] setStatusBarStyle:(style) animated:YES];
    
    currentStatusBarStyle = style;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.isDragged = YES;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    
    if (self.is3DTouchJump) return;
    
    if ((-self.scrollInsetTop - scrollView.contentOffset.y) / TopScrollDistance >= 1) {
        [self previousStory];
    }
    
    if ((self.webView.scrollView.mj_footer.state == MJRefreshStatePulling)) {
        
        if (!self.nextStoryBtn.enabled) return;
        [self nextStoryClick:nil];
    }
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return nil;
}

#pragma mark - <UIWebViewDelegate>
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    // 更新文章为已读状态
    [SQLiteManager updateReadStatusWithStoryID:self.storyID];
    
    [self.storyListVc reloadReadStoryWithIndexPath:self.indexPath];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    self.request = nil;
    
    webView.scrollView.scrollEnabled = YES;
    [self.loadingIndicatorView stopAnimating];
    
    self.topStatusBar.hidden = !(webView.scrollView.contentOffset.y >= 0);
    
    if (self.model.section != nil) {
        webView.scrollView.contentInset = UIEdgeInsetsMake(self.scrollInsetTop, 0, JKBarHeight + JKMarginTen * 3, 0);
    }
    
    // 获取网页中图片url
    [self getImageUrlsViaJs];
}

// 这里是js，主要目的实现对url的获取
- (void)getImageUrlsViaJs{
    //添加图片可点击js
    [self.webView evaluateJavaScript:@"function registerImageClickAction(){\
     var imgs=document.getElementsByTagName('img');\
     var length=imgs.length;\
     for(var i=0;i<length;i++){\
     img=imgs[i];\
     img.onclick=function(){\
     window.location.href='image-preview:'+this.src}\
     }\
     }" completionHandler:nil];
    [self.webView evaluateJavaScript:@"registerImageClickAction();" completionHandler:nil];
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSURL *url = navigationAction.request.URL;
    
    //预览图片
    if ([url.scheme isEqualToString:@"image-preview"]) {
        NSString* path = [url.absoluteString substringFromIndex:[@"image-preview:" length]];
        
        //path 就是被点击图片的url
        //path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [JKImageBrowserView showWithImageUrlStr:path];
        
        decisionHandler(WKNavigationActionPolicyCancel);
        
    }else if ([url.scheme isEqual:@"http"] || [url.scheme isEqual:@"mailto"] || [url.scheme isEqual:@"https"]) {
        
        if (self.request || [url.absoluteString containsString:@"daily_mp4"] || [url.absoluteString containsString:@"v.qq.com"] || [url.absoluteString containsString:@"video.qq.com"]) {
            
            decisionHandler(WKNavigationActionPolicyAllow);
            
        }else{
            
            JKBrowserViewController *browserVc = [[JKBrowserViewController alloc] init];
            browserVc.request = navigationAction.request;
            [self.navigationController pushViewController:browserVc animated:YES];
            decisionHandler(WKNavigationActionPolicyCancel);
        }
        
    }else{
        
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

// 点击详情底部合集view
- (void)tapbottomContainerView{
    SectionViewController *sectionVc = [[SectionViewController alloc] init];
    sectionVc.section = self.model.section;
    [self.navigationController pushViewController:sectionVc animated:YES];
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    self.currentSkinModel = currentSkinModel;
    
    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        
        self.view.backgroundColor = JKNightSkinColor;
        self.topStatusBar.backgroundColor = JKColor(60, 60, 60);
        self.bottomBarView.backgroundColor = JKNightSkinColor;
        self.bottomContainerView.backgroundColor = [JKNightSkinColor colorWithAlphaComponent:0.6];
        self.bottomContainerViewLabel.textColor = [UIColor whiteColor];
        self.coverView.hidden = NO;
        
        [[UIApplication sharedApplication] setStatusBarStyle:(UIStatusBarStyleLightContent) animated:YES];
        currentStatusBarStyle = UIStatusBarStyleLightContent;
        
    }else{ // 日间模式
        
        self.view.backgroundColor = [UIColor whiteColor];;
        self.topStatusBar.backgroundColor = [UIColor whiteColor];
        self.bottomBarView.backgroundColor = JKColor(237, 237, 237);
        self.bottomContainerView.backgroundColor = JKColor(237, 237, 237);
        self.bottomContainerViewLabel.textColor = [UIColor blackColor];
        self.coverView.hidden = YES;
        
        currentStatusBarStyle = (self.webView.scrollView.contentOffset.y >= 0) ? UIStatusBarStyleDefault : UIStatusBarStyleLightContent;
        [[UIApplication sharedApplication] setStatusBarStyle:(currentStatusBarStyle) animated:YES];
    }
}

- (void)dealloc{
    self.webView.scrollView.delegate = nil;
    currentStatusBarStyle = 1;
    
    if (self.isTop || ([[NSUserDefaults standardUserDefaults] boolForKey:JKReadPositionNoticeOffKey]) || self.stories.count == 0) {
        
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        
        return;
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JKLastReadIndexNotification object:self userInfo:@{JKLastReadIndexKey : self.indexPath}];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
